const request = require("request");
const { Op } = require("sequelize");

const wechat = appRequire('controllers/wxFWH/wechat');
const login = appRequire('controllers/user/login');
const userModel = appRequire('models/user');

// 暴露WeChat对象
module.exports = {
    sendWxFwhTemplateMsg,
    sendWarnGoodTemplateMsg, // 商品预警单独发送
};

async function sendWxFwhTemplateMsg(req) {
    let postData = req.body;
    let noticeUserIds = postData.noticeUserIds || []
    noticeUserIds.push(postData.uid)

    let thisUsers = await userModel.user.findAll({
        where: {
            identity: { [Op.ne]: "" },
            wxFwhId: { [Op.ne]: "" },
            disabled: 0,
            wxFwhMessage: 1,
            masterId: postData.uid
        },
        attributes: ['objectId'],
    })

    for (let thisUser of thisUsers) {
        let thisIndex = noticeUserIds.findIndex(thisUserId => thisUserId == thisUser.objectId)
        if (thisIndex == -1) noticeUserIds.push(thisUser.objectId)
    }
    for (let userId of noticeUserIds) {

        let body = Common.clone(req.body)
        body.userId = userId
        req.body = body
        if (postData.type == 1) {
            sendEnterTemplateMsg(req)
        } else if (postData.type == -1) {
            if (postData.extra_type == 2 && postData.isShop) { //自助下单
                sendOutBuyOnlineTemplateMsg(req)
            } else {
                sendOutTemplateMsg(req)
            }
        } else if (postData.type == 2) {//调拨单
            sendAllocationTemplateMsg(req)
        } else if (postData.type == 3) {//盘点单
            sendCountTemplateMsg(req)
        } else if (postData.type == 6) {//报修单
            sendFixedTemplateMsg(req)
        } else if (postData.type == -11) {//销售订单
            sendOutBuyLaterTemplateMsg(req)
        } else if (postData.type == 11) { //采购订单
            sendPurchaseLaterTemplateMsg(req)
        } else if (postData.type == -13) { //报价单
            sendGoodOutOfferTemplateMsg(req)
        }
    }
}

//保修单推送模板
async function sendFixedTemplateMsg(req) {
    let postData = req.body;

    let access_token = await wechat.getAccessToken();
    let url = `https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=` + access_token; //发送模板消息的接口

    let thisUser = await userModel.user.findOne({
        where: {
            objectId: postData.userId,
        },
        include: ["master", "staffRole"],
    })
    thisUser = Common.clone(thisUser)
    thisUser = await login.changeUserInfo(thisUser)

    if (thisUser.wxFwhId) {
        let rights = await login.changeRights(thisUser)
        if (rights.good.canSeeCostprice == false) {
            postData.haveGetMoney = 0
        }
        let openid = thisUser.wxFwhId
        let goodsNames = []
        for (let item of postData.goods) {
            goodsNames.push(item.goodsName)
        }
        let requestData = {
            touser: openid,
            template_id: '1XAV9p56JykUu95V6CSy2EaQ9VXqq8QXARvl_IoOr6E',
            url: "https://web.jimuzhou.top/pages/ApplicationFixed/user/fixedOrderDet?objectId=" + postData.orderId + "&uid=" + thisUser.objectId,
            data: {
                first: {
                    value: '您好，您有一笔报修单已经创建，请尽快处理！',
                    color: "#173177"
                },
                keyword1: {
                    value: postData.address.userName,
                    color: '#1d1d1d'
                },
                keyword2: {
                    value: postData.nowDay.split(" ")[0],
                    color: '#1d1d1d'
                },
                keyword3: {
                    value: postData.address.address,
                    color: '#1d1d1d'
                },
                keyword4: {
                    value: postData.beizhu,
                    color: '#1d1d1d'
                },
                remark: {
                    value: "",
                    color: '#173177'
                }
            }
        }

        request({
            url: url,
            method: 'post',
            body: JSON.stringify(requestData),
        }, function (error, res, body) {
            console.log(body)
            body = JSON.parse(body)
            if (!error && body.errcode == 0) {
                console.log("模板消息发送成功")
            }
        });
    }
}

//采购订单推送模板
async function sendPurchaseLaterTemplateMsg(req) {
    let postData = req.body;

    let access_token = await wechat.getAccessToken();
    let url = `https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=` + access_token; //发送模板消息的接口

    let thisUser = await userModel.user.findOne({
        where: {
            objectId: postData.userId,
        },
        include: ["master", "staffRole"],
    })
    thisUser = Common.clone(thisUser)
    thisUser = await login.changeUserInfo(thisUser)

    if (thisUser.wxFwhId) {
        let rights = await login.changeRights(thisUser)
        if (rights.good.canSeeCostprice == false) {
            postData.haveGetMoney = 0
        }
        let openid = thisUser.wxFwhId
        let goodsNames = []
        for (let item of postData.goods) {
            goodsNames.push(item.goodsName)
        }
        let requestData = {
            touser: openid,
            template_id: 'G1RvpMn1hn7IX-5YZoN1g_4D4FvjfP3ke_E8O8JWqyo',
            url: "https://web.jimuzhou.top/pages/orders/inDetail/purchaseLaterDetail?objectId=" + postData.orderId + "&uid=" + thisUser.objectId,
            data: {
                first: {
                    value: '您好，您有一笔采购订单已经创建，请尽快处理！',
                    color: "#173177"
                },
                keyword1: {
                    value: postData.orderNum,
                    color: '#1d1d1d'
                },
                keyword2: {
                    value: goodsNames.join(","),
                    color: '#1d1d1d'
                },
                keyword3: {
                    value: postData.capName,
                    color: '#1d1d1d'
                },
                keyword4: {
                    value: postData.haveGetMoney,
                    color: '#1d1d1d'
                },
                keyword5: {
                    value: postData.nowDay.split(" ")[0],
                    color: '#1d1d1d'
                },
                remark: {
                    value: postData.beizhu,
                    color: '#173177'
                }
            }
        }

        request({
            url: url,
            method: 'post',
            body: JSON.stringify(requestData),
        }, function (error, res, body) {
            body = JSON.parse(body)
            if (!error && body.errcode == 0) {
                console.log("模板消息发送成功")
            }
        });
    }
}

//销售订单推送模板
async function sendOutBuyLaterTemplateMsg(req) {
    let postData = req.body;

    let access_token = await wechat.getAccessToken();
    let url = `https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=` + access_token; //发送模板消息的接口

    let thisUser = await userModel.user.findByPk(postData.userId)

    if (thisUser.wxFwhId) {
        let goodsNames = []
        for (let item of postData.goods) {
            goodsNames.push(item.goodsName)
        }
        let openid = thisUser.wxFwhId
        let requestData = {
            touser: openid,
            template_id: 'd08aWSDYGpcFRZF2519pCUlcCEbI7eNfdOOpBDKPgmI',
            url: "https://web.jimuzhou.top/pages/orders/outDetail/SellLaterDetail?objectId=" + postData.orderId + "&uid=" + thisUser.objectId,
            data: {
                first: {
                    value: '您好，您有一笔销售订单已经创建，请尽快处理！',
                    color: "#173177"
                },
                keyword1: {
                    value: postData.orderNum,
                    color: '#1d1d1d'
                },
                keyword2: {
                    value: goodsNames.join(","),
                    color: '#1d1d1d'
                },
                keyword3: {
                    value: postData.capName,
                    color: '#1d1d1d'
                },
                keyword4: {
                    value: postData.opreater.nickName,
                    color: '#1d1d1d'
                },
                keyword5: {
                    value: postData.nowDay.split(" ")[0],
                    color: '#1d1d1d'
                },
                remark: {
                    value: postData.beizhu,
                    color: '#173177'
                }
            }
        }

        request({
            url: url,
            method: 'post',
            body: JSON.stringify(requestData),
        }, function (error, res, body) {
            body = JSON.parse(body)
            if (!error && body.errcode == 0) {
                console.log("模板消息发送成功")
            }
        });
    }
}

//推送入库模板消息
async function sendEnterTemplateMsg(req) {
    let postData = req.body;

    let access_token = await wechat.getAccessToken();
    let url = `https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=` + access_token; //发送模板消息的接口

    let thisUser = await userModel.user.findOne({
        where: {
            objectId: postData.userId,
        },
        include: ["master", "staffRole"],
    })
    thisUser = Common.clone(thisUser)
    thisUser = await login.changeUserInfo(thisUser)

    let pageUrl = "https://web.jimuzhou.top/pages/orders/inDetail/stockInDet"
    if (postData.extra_type == 2) { // 采购
        pageUrl = "https://web.jimuzhou.top/pages/orders/inDetail/purchaseDetail"
    } else if (postData.extra_type == 3) { // 销售退货
        pageUrl = "https://web.jimuzhou.top/pages/orders/outDetail/sellReturnDetail"
    }

    if (thisUser.wxFwhId) {
        let rights = await login.changeRights(thisUser)
        if (rights.good.canSeeCostprice == false) {
            postData.haveGetMoney = 0
        }
        let openid = thisUser.wxFwhId
        let goodsNames = []
        for (let item of postData.goods) {
            goodsNames.push(item.goodsName)
        }
        let requestData = {
            touser: openid,
            template_id: 'vGisyBuuQgztwhqwSdUdhYDaz05Cras2AuYF_-AYdQ4',
            url: pageUrl + "?objectId=" + postData.orderId + "&uid=" + thisUser.objectId,
            data: {
                first: {
                    value: '您好，您有商品' + postData.stockClass + '，请查收！',
                    color: "#173177"
                },
                keyword1: {
                    value: postData.capName || "未填写",
                    color: '#1d1d1d'
                },
                keyword2: {
                    value: postData.nowDay.split(" ")[0],
                    color: '#1d1d1d'
                },
                keyword3: {
                    value: goodsNames.join("，"),
                    color: '#1d1d1d'
                },
                keyword4: {
                    value: postData.real_num,
                    color: '#1d1d1d'
                },
                remark: {
                    value: postData.beizhu,
                    color: '#173177'
                }
            }
        }

        request({
            url: url,
            method: 'post',
            body: JSON.stringify(requestData),
        }, function (error, res, body) {
            console.log(body)
            body = JSON.parse(body)
            if (!error && body.errcode == 0) {
                console.log("模板消息发送成功")
            }
        });
    }
}

//推送出库模板消息
async function sendOutTemplateMsg(req) {
    let postData = req.body;

    let access_token = await wechat.getAccessToken();
    let url = `https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=` + access_token; //发送模板消息的接口

    let thisUser = await userModel.user.findByPk(postData.userId)

    let pageUrl = "https://web.jimuzhou.top/pages/orders/outDetail/stockOutDet"
    if (postData.extra_type == 2) { // 销售
        pageUrl = "https://web.jimuzhou.top/pages/orders/outDetail/SellDetail"
    } else if (postData.extra_type == 3) { // 采购退货
        pageUrl = "https://web.jimuzhou.top/pages/orders/inDetail/purchaseReturnDetail"
    }

    if (thisUser.wxFwhId) {
        let openid = thisUser.wxFwhId
        let goodsNames = []
        for (let item of postData.goods) {
            goodsNames.push(item.goodsName)
        }
        let requestData = {
            touser: openid,
            template_id: 'r-LUBMrdX9fsjtOZ-taMoQ_OHvVFNC3VxAU-_2E4fls',
            url: pageUrl + "?objectId=" + postData.orderId + "&uid=" + thisUser.objectId,
            data: {
                first: {
                    value: '您好，您有商品' + postData.stockClass + '，请查收！',
                    color: "#173177"
                },
                keyword1: {
                    value: postData.capName || "未填写",
                    color: '#1d1d1d'
                },
                keyword2: {
                    value: postData.nowDay.split(" ")[0],
                    color: '#1d1d1d'
                },
                keyword3: {
                    value: goodsNames.join("，"),
                    color: '#1d1d1d'
                },
                keyword4: {
                    value: postData.real_num,
                    color: '#1d1d1d'
                },
                keyword5: {
                    value: "未填写",
                    color: '#1d1d1d'
                },
                remark: {
                    value: postData.beizhu,
                    color: '#173177'
                }
            }
        }

        request({
            url: url,
            method: 'post',
            body: JSON.stringify(requestData),
        }, function (error, res, body) {
            body = JSON.parse(body)
            if (!error && body.errcode == 0) {
                console.log("模板消息发送成功")
            }
        });
    }
}


//推送盘点单模板消息
async function sendCountTemplateMsg(req) {
    let postData = req.body;

    let access_token = await wechat.getAccessToken();
    let url = `https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=` + access_token; //发送模板消息的接口

    let thisUser = await userModel.user.findByPk(postData.userId)

    if (thisUser.wxFwhId) {
        let openid = thisUser.wxFwhId
        let goodsNames = []
        for (let item of postData.goods) {
            goodsNames.push(item.goodsName)
        }
        let requestData = {
            touser: openid,
            template_id: 'Z4PT9getJ9Zq9sd9KatVsKbRdi9GY9GAkyCEKBiVD2Q',
            url: "https://web.jimuzhou.top/pages/orders/countDetail/countDetail?objectId=" + postData.orderId + "&uid=" + thisUser.objectId,
            data: {
                first: {
                    value: '您好，您有商品盘点成功，请查收！',
                    color: "#173177"
                },
                keyword1: {
                    value: postData.nowDay.split(" ")[0],
                    color: '#1d1d1d'
                },
                keyword2: {
                    value: goodsNames.join("，"),
                    color: '#1d1d1d'
                },
                remark: {
                    value: postData.beizhu,
                    color: '#173177'
                }
            }
        }

        request({
            url: url,
            method: 'post',
            body: JSON.stringify(requestData),
        }, function (error, res, body) {
            body = JSON.parse(body)
            if (!error && body.errcode == 0) {
                console.log("模板消息发送成功")
            }
        });
    }
}


//推送调拨单模板消息
async function sendAllocationTemplateMsg(req) {
    let postData = req.body;

    let access_token = await wechat.getAccessToken();
    let url = `https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=` + access_token; //发送模板消息的接口

    let thisUser = await userModel.user.findByPk(postData.userId)

    if (thisUser.wxFwhId) {
        let openid = thisUser.wxFwhId
        let goodsNames = []
        for (let item of postData.goods) {
            goodsNames.push(item.goodsName)
        }
        let requestData = {
            touser: openid,
            template_id: 'VN1-PX3bctAKHUY-snTMsW_gYiUS5gGs0PgwWdPQvAs',
            url: "https://web.jimuzhou.top/pages/orders/allocationDetail/allocationDetail?objectId=" + postData.orderId + "&uid=" + thisUser.objectId,
            data: {
                first: {
                    value: '您好，您有商品调拨成功，请查收！',
                    color: "#173177"
                },
                keyword1: {
                    value: postData.nowDay.split(" ")[0],
                    color: '#1d1d1d'
                },
                keyword2: {
                    value: postData.real_num,
                    color: '#1d1d1d'
                },
                keyword3: {
                    value: postData.outStockName,
                    color: '#1d1d1d'
                },
                keyword4: {
                    value: postData.inStockName,
                    color: '#1d1d1d'
                },
                keyword5: {
                    value: postData.status ? "已审核" : "未审核",
                    color: '#1d1d1d'
                },
                remark: {
                    value: postData.beizhu,
                    color: '#173177'
                }
            }
        }

        request({
            url: url,
            method: 'post',
            body: JSON.stringify(requestData),
        }, function (error, res, body) {
            body = JSON.parse(body)
            if (!error && body.errcode == 0) {
                console.log("模板消息发送成功")
            }
        });
    }
}

//推送报价单模板消息
async function sendGoodOutOfferTemplateMsg(req) {
    let postData = req.body;

    let access_token = await wechat.getAccessToken();
    let url = `https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=` + access_token; //发送模板消息的接口

    let thisUser = await userModel.user.findByPk(postData.userId)

    if (thisUser.wxFwhId) {
        let openid = thisUser.wxFwhId
        let goodsNames = []
        for (let item of postData.goods) {
            goodsNames.push(item.goodsName)
        }
        let requestData = {
            touser: openid,
            template_id: '4ilh0DKG1SMsvQVjcyORd78fbSvAdJcJFr20Rjhy_Ho',
            url: "https://web.jimuzhou.top/pages/orders/outDetail/sellOfferDetail?objectId=" + postData.orderId + "&uid=" + thisUser.objectId,
            data: {
                first: {
                    value: '您好，您有新的报价单，请查收！',
                    color: "#173177"
                },
                keyword1: {
                    value: postData.capName,
                    color: '#1d1d1d'
                },
                keyword2: {
                    value: "报价单",
                    color: '#1d1d1d'
                },
                keyword3: {
                    value: postData.address.address || "无",
                    color: '#1d1d1d'
                },
                keyword4: {
                    value: postData.createdAt,
                    color: '#1d1d1d'
                },
                remark: {
                    value: postData.nowDay.split(" ")[0],
                    color: '#173177'
                }
            }
        }

        request({
            url: url,
            method: 'post',
            body: JSON.stringify(requestData),
        }, function (error, res, body) {
            body = JSON.parse(body)
            if (!error && body.errcode == 0) {
                console.log("模板消息发送成功")
            }
        });
    }
}


//自助下单推送模板
async function sendOutBuyOnlineTemplateMsg(req) {
    let postData = req.body;

    let access_token = await wechat.getAccessToken();
    let url = `https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=` + access_token; //发送模板消息的接口

    let thisUser = await userModel.user.findByPk(postData.userId)

    if (thisUser.wxFwhId) {
        let openid = thisUser.wxFwhId
        let goodsNames = []
        for (let item of postData.goods) {
            goodsNames.push(item.goodsName)
        }
        let requestData = {
            touser: openid,
            template_id: 'et3gJ8u7q8Q4S59RnwgqQ2LDvirGMQhPvmZlkQeSEwI',
            url: "https://web.jimuzhou.top/pages/orders/outDetail/SellDetail?objectId=" + postData.orderId + "&uid=" + thisUser.objectId,
            data: {
                first: {
                    value: '您好，您有一笔新的自助下单，请尽快处理！',
                    color: "#173177"
                },
                keyword1: {
                    value: postData.orderNum,
                    color: '#1d1d1d'
                },
                keyword2: {
                    value: postData.capName || "未填写",
                    color: '#1d1d1d'
                },
                keyword3: {
                    value: postData.realMoney,
                    color: '#1d1d1d'
                },
                keyword4: {
                    value: postData.nowDay.split(" ")[0],
                    color: '#1d1d1d'
                },
                keyword5: {
                    value: postData.beizhu,
                    color: '#1d1d1d'
                },
                remark: {
                    value: "",
                    color: '#173177'
                }
            }
        }

        request({
            url: url,
            method: 'post',
            body: JSON.stringify(requestData),
        }, function (error, res, body) {
            body = JSON.parse(body)
            if (!error && body.errcode == 0) {
                console.log("模板消息发送成功")
            }
        });
    }
}


//预警推送推送模板
async function sendWarnGoodTemplateMsg(req) {
    let postData = req.body;

    let access_token = await wechat.getAccessToken();
    let url = `https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=` + access_token; //发送模板消息的接口

    let thisUser = await userModel.user.findByPk(postData.uid)

    if (thisUser.wxFwhId) {
        let openid = thisUser.wxFwhId
        let requestData = {
            touser: openid,
            template_id: 'NTF8usa57S-lx62m9iR2Pzbb-6sm18LHZ7pE9Gnm4iQ',
            url: "https://web.jimuzhou.top/pages/stock/search/warnGoods",
            data: {
                first: {
                    value: '您好，您有产品预警了',
                    color: "#173177"
                },
                keyword1: {
                    value: postData.goodsNames,
                    color: '#1d1d1d'
                },
                keyword2: {
                    value: dateFormat(new Date().getTime(), 'yyyy-mm-dd HH:MM:ss'),
                    color: '#1d1d1d'
                },
                remark: {
                    value: "请登录平台查看",
                    color: '#173177'
                }
            }
        }

        request({
            url: url,
            method: 'post',
            body: JSON.stringify(requestData),
        }, function (error, res, body) {
            body = JSON.parse(body)
            if (!error && body.errcode == 0) {
                console.log("模板消息发送成功")
            }
        });
    }
}